import android.util.Log
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
import okio.IOException
import java.nio.charset.Charset

class MyLoggingInterceptor : Interceptor {
    @Throws(IOException::class) override fun intercept(chain: Chain): Response {
        val original: Request = chain.request()
        val response: Response = chain.proceed(original)
        Log.i(
            TAG, java.lang.String.format(
            "...\n请求链接：%s\n请求头：%s\n请求参数：%s\n请求响应%s", original.url, getRequestHeaders(original),
            getRequestInfo(original), getResponseInfo(response)
        )
        )
        return response
    }

    /**
     * 打印请求头
     *
     * @param request 请求的对象
     */
    private fun getRequestHeaders(request: Request?): String {
        val str = ""
        if (request == null) {
            return str
        }
        val headers: Headers = request.headers ?: return str
        return headers.toString()
    }

    /**
     * 打印请求消息
     *
     * @param request 请求的对象
     */
    private fun getRequestInfo(request: Request?): String {
        var str = ""
        if (request == null) {
            return str
        }
        val requestBody: RequestBody = request.body ?: return str
        try {
            val bufferedSink = Buffer()
            requestBody.writeTo(bufferedSink)
            val charset: Charset = Charset.forName("utf-8")
            str = bufferedSink.readString(charset)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return str
    }

    /**
     * 打印返回消息
     *
     * @param response 返回的对象
     */
    private fun getResponseInfo(response: Response?): String {
        var str = ""
        if (response == null || !response.isSuccessful) {
            return str
        }
        val responseBody: ResponseBody = response.body!!
        val contentLength = responseBody.contentLength()
        val source = responseBody.source()
        try {
            source.request(Long.MAX_VALUE) // Buffer the entire body.
        } catch (e: IOException) {
            e.printStackTrace()
        }
        val buffer: Buffer = source.buffer()
        val charset: Charset = Charset.forName("utf-8")
        if (contentLength != 0L) {
            str = buffer.clone().readString(charset)
        }
        return str
    }

    companion object {
        private const val TAG = "MyLoggingInterceptor"
    }
}